import {
  EllipsisOutlined,
  FilterOutlined,
  CaretUpOutlined,
  CaretDownOutlined,
} from '@ant-design/icons';
import { useDebounceFn, useUpdate } from 'ahooks';
import {
  Tree,
  Pagination,
  PaginationProps,
  Dropdown,
  Button,
  MenuProps,
  TreeProps,
  Col,
  Row,
  message,
  Checkbox,
  CheckboxProps,
  Spin,
  Switch,
  Menu,
} from 'antd';
import { memo, useEffect, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import datasetService from '@/api/services/datasetService';
import { CollectionPreviewInfoRes, DatasetTypeEnum } from '@/common';
import EmptyPage from '@/components/empty/EmptyPage';
import { SvgIcon } from '@/components/icon';
import TipsModals from '@/components/modals/TipsModals';
import NotData from '@/components/NotData';
import useWindowWidth from '@/hooks/event/use-window-width';
import FilePreviewDrawer from '@/pages/components/fileviewer/FilePreviewDrawer';
import { useDatasets } from '@/store/datasetsStore';
import { useDatasetStore } from '@/store/datasetStore';
import { Size } from '@/types/common';
import { DatasetEvent, TreeData } from '@/types/dataset';
import { formatData } from '@/utils/time';
import { transformToTreeItems, getNodeParent, getNodeParentType, filterTree } from '@/utils/tree';

import { DatasetsContext } from '../context';
import '../styles/datasetsTreeList.scss';
import { getDatasetIcon } from '../utils/icon';
import { getStatus, getIsEditPermission } from '../utils/status';

import DatasetApproveModal from './DatasetApproveModal';
import DeleteConfirmModal from './DeleteConfirmModal';

import usePermission from '@/hooks/event/usePermission';
import { useUserInfo } from '@/store/userStore';
import { useRouter, useParams } from '@/router/hooks';

import ExpirationTimeModal from './ExpirationTimeModal';

import useModal from '@/hooks/use-modal/useModal';
import { useInitializeData } from '@/store/configStore';

interface Props {
  showMoveTo?: () => void;
  onRenameClicked?: (name: string) => void;
  onDeleteClicked?: (key: string, type: string) => void;
  onRewareHousingClicked?: (key: string, type: string) => void;
  parentSize: Size;
  dataLoading?: boolean;
  createDataset?: boolean;
  onUpdateClicked?: (node: TreeData, isUpdateChild?: boolean) => void;
  onShowCollectionDetail?: (id: string, name: string) => void;
  onChangeType: (node: TreeData, flag: boolean) => void;
  searchData?: string;
  onRenameType?: any;
}

function DatasetsTreeList({
  showMoveTo,
  onRenameClicked,
  onDeleteClicked,
  onRewareHousingClicked,
  parentSize,
  dataLoading,
  createDataset,
  onUpdateClicked,
  onShowCollectionDetail,
  onChangeType,
  searchData = '',
  onRenameType,
}: Props) {
  const {
    selectedTreeNode,
    selectedTreeData,
    fullTreeData,
    selectedTreeKeys,
    event$,
    checkedTreeDatas,
    currentEditTreeData,
    setSelectedTreeNode,
    setSelectedTreeData,
    setSelectedTreeKeys,
    setCurrentEditTreeData,
    setCheckedTreeDatas,
    setFullTreeData,
    isDelete,
    setIsDelete,
    setUpdateExpiredTime,
    users,
  } = useContextSelector(DatasetsContext, (s) => s);
  const {
    parentIdstore,
    allDatasets,
    allDatasetsTotal,
    expandedKeys,
    loadCollections,
    loadAllDatasets1,
    getParentId,
    getDatasetStatus,
    ungroupedId,
  } = useDatasetStore();
  const { expandKeys } = useDatasets();
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  const [showList, setShowList] = useState(false);
  const [isDataset, setIsDataset] = useState(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [batchDelete, setBatchDelete] = useState(false);
  const [searchValue, setSearchValue] = useState('');
  const [isCheckedAll, setIsCheckedAll] = useState(false);
  const [loading, setLoading] = useState(false);
  const [isPreview, setIsPreview] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [treeDataList, setTreeDataList] = useState<[]>([]);
  const [isReapproval, setIsReapproval] = useState(false);
  const [approvalData, setApprovalData] = useState<any>([]);
  const router = useRouter();
  const { isPc } = useWindowWidth();
  const update = useUpdate();
  const { isPermit } = usePermission();
  const { username, groupId, userId } = useUserInfo() as {
    username: string;
    groupId: string;
    userId: string;
  };
  const initializeData = useInitializeData();
  const { appId = '' } = useParams() as { appId: string };
  const isRoot = username == 'root';
  const user_id = userId;
  const [fileType, setFileType] = useState('dataset');
  const [flag, setFlag] = useState(false);
  const [showType, setShowType] = useState('');
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: '启用',
    },
    {
      key: '2',
      label: '停用',
    },
  ];
  const modal = useModal('timeModal', 'deleteModal');
  const [deleteNode, setDeleteNode] = useState<TreeData>([]);

  // 新增本地筛选状态
  const [statusFilter, setStatusFilter] = useState<string | undefined>(undefined);
  const [forbidFilter, setForbidFilter] = useState<string | undefined>(undefined);
  // 状态筛选项
  const statusOptions = [
    { text: '全部', value: undefined },
    { text: '审批中', value: 'upload_publish' },
    { text: '上传驳回', value: 'upload_reject' },
    { text: '删除驳回', value: 'delete_reject' },
    { text: '已入库', value: 'upload_pass' },
    { text: '删除审批中', value: 'delete_publish' },
  ];
  // 启/停用筛选项
  const forbidOptions = [
    { text: '全部', value: undefined },
    { text: '启用', value: 'enabled' },
    { text: '停用', value: 'disabled' },
  ];

  // 新增日期排序状态
  const [dateSortOrder, setDateSortOrder] = useState<'ascend' | 'descend' | undefined>(undefined);
  // 日期排序点击逻辑
  const handleDateSortClick = () => {
    setDateSortOrder((prev) => {
      if (prev === undefined) return 'descend';
      if (prev === 'descend') return 'ascend';
      return undefined;
    });
  };

  const moveTo = (node: TreeData) => {
    setCurrentEditTreeData(node);
    showMoveTo && showMoveTo();
  };

  const getMenus = (node: TreeData) => {
    const { type, id, reviewStatus, fileId, operator, experiodDays } = node;
    const lable =
      type === 'folder' ? '删除此文件夹' : type === 'dataset' ? '删除此知识库' : '删除文件';
    // 是否是文档
    const isMoveto = type === 'folder' || type === 'dataset';
    // 重新审批
    const isApprove =
      (reviewStatus === 'upload_reject' || reviewStatus === 'delete_reject') &&
      node.groupId === groupId &&
      !isRoot;
    // 删除
    const showFileDelete =
      fileId != undefined && reviewStatus === 'delete_reject' && node.groupId === groupId;
    // 忽略
    const showIgnore = reviewStatus === 'delete_reject' && node.groupId === groupId;
    return [
      // {
      //   key: '1',
      //   label: type === 'dataset' ? '编辑' : '修改名称',
      //   onClick: (e) => {
      //     if (type === 'dataset') {
      //       e.domEvent.stopPropagation();
      //       setCurrentEditTreeData(node);
      //       onUpdateClicked && onUpdateClicked(node);
      //     } else if (type === 'folder') {
      //       e.domEvent.stopPropagation();
      //       setCurrentEditTreeData(node);
      //       onUpdateClicked && onUpdateClicked(node);
      //       // onRenameClicked && onRenameClicked(node.name);
      //     } else {
      //       e.domEvent.stopPropagation();
      //       setCurrentEditTreeData(node);
      //       onRenameClicked && onRenameClicked(node.name);
      //     }
      //   },
      // },
      ...(!isMoveto && reviewStatus === 'upload_pass'
        ? [
            {
              key: '2',
              label: (
                <div className="flex items-center">
                  <SvgIcon icon="message-ic24" size={16} className="mr-1" />
                  <span>{experiodDays != null ? '修改过期时间' : '添加过期时间'}</span>
                </div>
              ),
              onClick: (e: any) => {
                e.domEvent.stopPropagation();
                setUpdateExpiredTime(node);
                modal.timeModal.open();
              },
            },
          ]
        : []),
      ...(isRoot
        ? [
            {
              key: '3',
              label: (
                <div className="flex items-center">
                  <SvgIcon icon="message-ic23" size={16} className="mr-1" />
                  <span>重新入库</span>
                </div>
              ),
              onClick: (e: any) => {
                e.domEvent.stopPropagation();
                if (type === 'file') {
                  onRewareHousingClicked && onRewareHousingClicked(node.fileId, type);
                } else {
                  onRewareHousingClicked && onRewareHousingClicked(node.id || node?._id, type);
                }
              },
            },
          ]
        : []),
      ...(isApprove
        ? [
            {
              key: '4',
              label: (
                <div className="flex items-center">
                  <SvgIcon icon="message-ic21" size={16} className="mr-1" />
                  <span>重新审批</span>
                </div>
              ),
              onClick: (e: any) => {
                e.domEvent.stopPropagation();
                setIsReapproval(true);
                setApprovalData(node);
              },
            },
          ]
        : []),
      ...(showIgnore
        ? [
            {
              key: '5',
              label: (
                <div className="flex items-center">
                  <SvgIcon icon="message-ic21" size={16} className="mr-1" />
                  <span>忽略</span>
                </div>
              ),
              onClick: (e: any) => {
                e.domEvent.stopPropagation();
                changeIgnore(node);
              },
            },
          ]
        : []),
      ...(showFileDelete
        ? []
        : [
            {
              key: '6',
              label: (
                <span className="flex items-center text-@error-color">
                  {/* 红色警示色 */}
                  <SvgIcon icon="message-ic3" size={16} className="mr-1" />
                  {lable}
                </span>
              ),
              onClick: (e: any) => {
                e.domEvent.stopPropagation();

                if (!getIsEditPermission(users, node) && node.groupId !== ungroupedId) {
                  message.info('当前用户没有该文档的编辑权限');
                  return;
                }
                if (
                  (reviewStatus == 'upload_pass' || reviewStatus == 'delete_pass') &&
                  initializeData.is_knowledge_manager
                ) {
                  setCurrentEditTreeData(node);
                  // setDeleteNode(node);
                  modal.deleteModal.open();
                } else {
                  singleDelete(node);
                }
              },
            },
          ]),
    ];
  };
  const iconMargin = 'mb-1 ml-1 mr-1 mt-1';
  const titleRender = (node: TreeData) => {
    const {
      id,
      name,
      key,
      type,
      children,
      updateTime,
      count,
      forbid,
      createTime,
      dataset_tags,
      groupName,
      reviewStatus,
      operator,
      fileId,
      experiodDays,
    } = node;
    const isMoveto = type === 'folder' || type === 'dataset';
    const isReviewStatusPublish =
      reviewStatus === 'upload_publish' || reviewStatus === 'delete_publish';

    const isEdit = getIsEditPermission(users, node);
    const isUngrouped = node.groupId === ungroupedId; // 未分组id
    if (isPc) {
      return (
        <Row
          justify="space-between"
          align="bottom"
          className={`flex items-center p-1  ${
            isReviewStatusPublish && !isMoveto ? 'bg-[#f0ede9]' : ''
          } `}
        >
          <Col span={showType === 'dataset' ? 4 : 4}>
            <div className="mr-auto flex">
              <div className="mr-2 flex-shrink-0 items-center justify-center rounded-lg">
                {getDatasetIcon(node, expandedKeys, true)}
              </div>
              <div className="self-center truncate">{name}</div>
            </div>
          </Col>
          {/* {isPc && ( */}
          {showType === 'dataset' && (
            <>
              <Col span={4}>
                <div className="ml-2 self-center truncate">{dataset_tags?.join('、')}</div>
              </Col>
              <Col span={4}>
                <div className="ml-2 self-center truncate">{groupName}</div>
              </Col>
            </>
          )}
          {!isMoveto && (
            <Col span={2}>
              <div className="ml-1 self-center truncate">
                {experiodDays != null ? experiodDays : '-'}
              </div>
            </Col>
          )}
          <Col span={4}>
            <div className="ml-2 self-center truncate">
              {formatData(createTime)}
              {/* {dayjs(create_time).format('YYYY-MM-DD HH:mm:ss')} */}
            </div>
          </Col>
          <Col span={2}>
            {isDataset && showType == 'folader' && (
              <div className=" self-center truncate">{getStatus(reviewStatus as string)}</div>
            )}
          </Col>
          <Col span={2}>
            {/* {isDataset && (
              <Dropdown
                trigger={isPc ? ['hover'] : ['click']}
                menu={{
                  items,
                  selectable: true,
                  selectedKeys: [!forbid ? '1' : '2'],
                  onClick: async (item) => {
                    item.domEvent.stopPropagation();
                    if (!isPermit) {
                      message.info('权限暂不支持该操作');
                      return;
                    }
                    await datasetService.setForBid({ id: node._id, forbid: !forbid });

                    // await datasetService.updateDatasetCollection({
                    //   forbid: item.key == '2',
                    //   id,
                    // });

                    event$?.emit(DatasetEvent.UPDATECOLLECTION);
                  },
                }}
              >
                {showType == 'folader' && (
                  <Typography.Link
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    <Space
                      style={{
                        width: '100px',
                        color: forbid ? '#474c5F' : '#6D35FF',
                      }}
                    >
                      {!forbid ? '启用' : '停用'}
                      <DownOutlined />
                       
                    </Space>
                  </Typography.Link>
                )}
              </Dropdown>
            )} */}

            {isDataset && showType == 'folader' && (
              <Switch
                checked={!forbid} // 更符合antd的命名规范
                onChange={async (checked, event) => {
                  event.stopPropagation();
                  if (!isPermit) {
                    message.info('权限暂不支持该操作');
                    return;
                  }
                  await datasetService.setForBid({ id: node._id, forbid: !checked });
                  event$?.emit(DatasetEvent.UPDATECOLLECTION);
                }}
                disabled={!isEdit && !isUngrouped}
                // checkedChildren="启用"
                // unCheckedChildren="停用"
                style={{
                  // backgroundColor: forbid ? '#474c5F' : '#6D35FF',
                  background: forbid
                    ? '#C9CDD4 '
                    : 'linear-gradient(90deg, #1B6DFA 0%, #00D0FE 181.25%)',
                  // minWidth: '60px'
                }}
              />
            )}
          </Col>
          <Col span={4} className="flex ">
            <div className="ml-[-10px] flex">
              <div
                onClick={(e) => {
                  if (!isMoveto && isReviewStatusPublish) {
                    return;
                  }
                  e.stopPropagation();
                  if (!isEdit && !isUngrouped) {
                    message.info('当前用户没有该文档的编辑权限');
                    return;
                  }
                  if (type === 'dataset') {
                    // e.domEvent.stopPropagation();
                    setCurrentEditTreeData(node);
                    onUpdateClicked && onUpdateClicked(node);
                  } else if (type === 'folder') {
                    // e.domEvent.stopPropagation();
                    setCurrentEditTreeData(node);
                    onUpdateClicked && onUpdateClicked(node);
                    // onRenameClicked && onRenameClicked(node.name);
                  } else {
                    // e.domEvent.stopPropagation();
                    setCurrentEditTreeData(node);
                    onRenameClicked && onRenameClicked(node.name);
                  }
                }}
                className={`${
                  !isMoveto && isReviewStatusPublish ? 'cursor-not-allowed' : ''
                } mr-6 flex items-center justify-center rounded-lg text-@brand-color`}
              >
                <span className={!isEdit && !isUngrouped ? 'text-text-3' : ''}>
                  <SvgIcon
                    icon={!isMoveto && isReviewStatusPublish ? 'singleedit_un' : 'singleedit'}
                    className="mr-1"
                  />
                  编辑
                </span>
              </div>

              {isMoveto && (
                <div
                  onClick={(e) => {
                    if (!isMoveto && isReviewStatusPublish) {
                      return;
                    }
                    e.stopPropagation();
                    if (!isEdit && !isUngrouped) {
                      message.info('当前用户没有该文档的编辑权限');
                      return;
                    }
                    // e.domEvent.stopPropagation();
                    moveTo(node);
                  }}
                  className={`${
                    !isMoveto && isReviewStatusPublish ? 'cursor-not-allowed' : ''
                  } mr-6 flex items-center justify-center rounded-lg text-@brand-color`}
                >
                  <span className={!isEdit && !isUngrouped ? 'text-text-3' : ''}>
                    <SvgIcon
                      icon={!isMoveto && isReviewStatusPublish ? 'moveicon_un' : 'moveicon'}
                      className="mr-1"
                    />
                    移动
                  </span>
                </div>
              )}

              <div className="ml-[-4px] flex items-center">
                <Dropdown
                  menu={{ items: getMenus(node) }}
                  trigger={isPc ? ['hover'] : ['click']}
                  placement="bottomLeft"
                  disabled={(!isMoveto && isReviewStatusPublish) || (!isEdit && !isUngrouped)}
                >
                  {/* <Button
                    type="text"
                    className={'mr-8'}
                    icon={<EllipsisOutlined />}
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    更多
                  </Button> */}
                  <div
                    className={`${
                      (!isMoveto && isReviewStatusPublish) || (!isEdit && !isUngrouped)
                        ? 'cursor-not-allowed'
                        : ''
                    }  flex items-center text-@brand-color`}
                    onClick={(e) => {
                      e.stopPropagation();
                    }}
                  >
                    <span className={!isEdit && !isUngrouped ? 'text-text-3' : ''}>
                      <EllipsisOutlined className="mr-1" />
                      更多
                    </span>
                  </div>
                </Dropdown>
              </div>
            </div>
          </Col>
        </Row>
      );
    }
    return (
      <span className="title items-center">
        <div className="flex items-center">
          <div className="mr-2 flex-shrink-0 items-center justify-center rounded-lg">
            {getDatasetIcon(node, expandedKeys, true)}
          </div>
          <span style={{ maxWidth: `${parentSize.width * 0.65}px` }} className="titleContent rang2">
            {name}
          </span>
        </div>
        <div className="absolute right-0 top-2">
          <Dropdown
            menu={{ items: getMenus(node) }}
            trigger={isPc ? ['hover'] : ['click']}
            placement="bottomLeft"
          >
            <Button
              type="text"
              icon={<EllipsisOutlined />}
              onClick={(e) => {
                e.stopPropagation();
              }}
            />
          </Dropdown>
        </div>
      </span>
    );
  };

  const updateSelectedDatasetTree = (node: TreeData) => {
    const tree: TreeData[] = [];
    tree.push(node);
    getNodeParent(tree, node);
    if (tree && tree.length > 0) {
      setSelectedTreeData([...selectedTreeData, ...tree]);
    }
  };

  const previewFile = (res: CollectionPreviewInfoRes) => {
    if (res.type == 'link') {
      window.open(res.url);
    } else if (res.type == 'file') {
      setLoading(true);
      setIsPreview(true);
      setPreviewUrl(`${res.url}&officePreviewType=pdf`);
      // window.open(res.url + "&officePreviewType=pdf");
    }
  };

  const onSelect: TreeProps['onSelect'] = async (selectedKeys: any, info: any) => {
    if (
      info.node.type !== 'folder' &&
      info.node.type !== 'dataset' &&
      !getIsEditPermission(users, info.node) &&
      info.node.groupId !== ungroupedId
    ) {
      message.info('当前用户没有该文档的编辑权限');
      return;
    }
    getDatasetStatus(info.node.reviewStatus);
    // 点击了文件或知识库
    onChangeType(info, setFlag(!flag));
    if (info.node.type != 'folder' && info.node.type != 'dataset') {
      onShowCollectionDetail &&
        onShowCollectionDetail(info.node.fileId || info.node.collectionId, info.node.name);
      !onShowCollectionDetail &&
        router.push(
          `/know/datasets/collection/detail?collectionId=${info.node.fileId}&name=${info.node.name}`,
        );
      return;
    }
    // 写入浏览器缓存
    getParentId(selectedKeys[0]);
    setFileType(info.node.type); // 存储一下文件的类型
    updateSelectedDatasetTree(info.node);
    setSelectedTreeNode(info.node);
  };

  const onCheck: TreeProps['onCheck'] = (checkedKeys: any, info: any) => {
    if (info.node.reviewStatus === 'delete_reject') {
      message.warning('该知识库处于删除驳回状态，无法选中');
      return;
    }

    setSelectedTreeKeys(checkedKeys.checked);
    setCheckedTreeDatas(info.checkedNodes);
  };

  const fetchCollections = async () => {
    try {
      setLoading(true); // 加载中
      setShowList(false);
      let res: any = '';

      if (parentIdstore && fileType === 'dataset') {
        res = await datasetService.getDatasetFileList({
          datasetId: parentIdstore,
          page,
          page_size: pageSize,
          offset: (page - 1) * pageSize,
          searchText: searchData,
          app_id: appId,
        });
        setShowType('folader');
        // const treeItems = transformToTreeItems(res.list, undefined, true);
        // console.log(treeItems);
        // return
      } else {
        // 获取知识库数据
        res = await loadAllDatasets1({
          parentId: parentIdstore,
          page,
          page_size: pageSize,
          offset: (page - 1) * pageSize,
          searchText: searchData,
          groupId,
          isPage: true,
          app_id: appId,
        });
        setShowType('dataset');
      }
      const treeItems = transformToTreeItems(res.list, undefined, true);
      setFullTreeData(treeItems);
      setTotal(res.total);
      // setFileType('folder')  //更新一下文件的类型
      if (treeItems.length > 0) {
        setShowList(true);
      }

      // if (selectedTreeNode) {
      //   const { id } = selectedTreeNode;
      //   const parent = getNodeParentType(selectedTreeNode.parent, 'dataset');
      //   if (selectedTreeNode.type == 'dataset' || parent) {
      //     setLoading(true);
      //     const res = parent
      //       ? await loadCollections({
      //         searchText: searchValue,
      //         datasetId: parent.id ?? '',
      //         pageNum: page,
      //         pageSize,
      //         parentId: id,
      //       })
      //       : await loadCollections({
      //         searchText: searchValue,
      //         datasetId: id,
      //         pageNum: page,
      //         pageSize,
      //       });

      //     const data = await res.data;
      //     if (data) {
      //       console.log(data, 'data');

      //       const datas = transformToTreeItems(data, selectedTreeNode);
      //       selectedTreeNode.children = datas;
      //       setTotal(res.total);
      //       update();
      //     }
      //   }
      // }
    } catch (error) {
      console.error(error);
    } finally {
      setTimeout(() => {
        setLoading(false);
      }, 500);
    }
  };

  const { run } = useDebounceFn(
    async () => {
      await fetchCollections();
    },
    { wait: 100 },
  );

  const onChange: PaginationProps['onChange'] = (page, pageSize) => {
    setPage(page);
    setPageSize(pageSize);
  };

  const clearRowSelection = () => {
    setIsCheckedAll(false);
    setSelectedTreeKeys([]);
    setCheckedTreeDatas([]);
  };

  const getTreeData = () => {
    // if (!selectedTreeNode) {
    //   return fullTreeData.filter((item) => item.type != DatasetTypeEnum.api);
    // }
    // return selectedTreeNode?.children;
    return fullTreeData.filter((item) => item.type != DatasetTypeEnum.api);
  };

  // 本地过滤+排序数据
  const filteredTreeData = getTreeData()
    .filter((item) => {
      let statusOk = true;
      let forbidOk = true;
      if (statusFilter) {
        statusOk = item.reviewStatus === statusFilter;
      }
      if (forbidFilter) {
        forbidOk = forbidFilter === 'enabled' ? !item.forbid : item.forbid;
      }
      return statusOk && forbidOk;
    })
    .sort((a, b) => {
      if (!dateSortOrder) return 0;
      const aTime = new Date(a.createTime).getTime();
      const bTime = new Date(b.createTime).getTime();
      if (dateSortOrder === 'ascend') return aTime - bTime;
      if (dateSortOrder === 'descend') return bTime - aTime;
      return 0;
    });

  // 表头筛选下拉渲染
  const renderHeaderWithFilter = (
    label: string,
    options: any[],
    value: string | undefined,
    onChange: (v: string | undefined) => void,
  ) => (
    <div className="flex items-center">
      <span>{label}</span>
      <Dropdown
        overlay={
          <Menu
            selectedKeys={[value || '全部']}
            onClick={({ key }) => onChange(key === '全部' ? undefined : key)}
            items={options.map((opt) => ({ key: opt.value ?? '全部', label: opt.text }))}
          />
        }
        trigger={['click']}
      >
        <Button
          type="text"
          icon={<FilterOutlined className={`${value ? 'text-@brand-color' : 'text-text-3'}`} />}
        />
      </Dropdown>
    </div>
  );

  // 日期表头渲染
  const renderDateSortTitle = () => (
    <span
      className="inline-flex cursor-pointer select-none items-center"
      onClick={handleDateSortClick}
    >
      创建日期
      <span className="ml-1 flex flex-col text-xs leading-none">
        <CaretUpOutlined
          style={{
            color: dateSortOrder === 'ascend' ? '#1677ff' : '#bfbfbf',
            fontSize: 10,
            marginBottom: -2,
          }}
        />
        <CaretDownOutlined
          style={{
            color: dateSortOrder === 'descend' ? '#1677ff' : '#bfbfbf',
            fontSize: 10,
            marginTop: -2,
          }}
        />
      </span>
    </span>
  );

  useEffect(() => {
    run();
    // if (!selectedTreeNode) {
    //   setShowList(true);
    // }
    setIsCheckedAll(false);
    setSearchValue('');
    clearRowSelection();
    setPage(1);
    setPageSize(10);
    setTotal(0);
    const parent = getNodeParentType(selectedTreeNode?.parent, 'dataset');
    if (parent) {
      setIsDataset(true);
    } else {
      const isDataset = selectedTreeNode?.type == 'dataset';
      setIsDataset(isDataset);
    }
  }, [selectedTreeNode]);

  useEffect(() => {
    setIsCheckedAll(false);
    setSelectedTreeKeys([]);
    run();
  }, [page, pageSize, createDataset]);

  useEffect(() => {
    checkPage();
  }, [page, pageSize, total]);

  useEffect(() => {
    setPage(1);
    setPageSize(10);
    run();
  }, [searchData, createDataset]);

  useEffect(() => {
    setFileType(onRenameType?.type);
    run();
  }, [onRenameType]);

  useEffect(() => {
    if (selectedTreeNode) {
      // setShowList(
      //   !!(
      //     selectedTreeNode &&
      //     selectedTreeNode?.children &&
      //     selectedTreeNode?.children?.length > 0
      //   ),
      // );
      // run();
      update();
    }
  }, [selectedTreeNode?.children]);

  event$?.useSubscription((val) => {
    run();
  });

  const onStatusClicked = async (forbid: boolean) => {
    if (!isPermit) {
      message.info('权限暂不支持该操作');
      return;
    }
    const promises = checkedTreeDatas.map(async (item) => {
      if (forbid != item.forbid) {
        await datasetService.setForBid({
          forbid: !!forbid,
          id: item._id,
        });
      }
    });

    await Promise.all(promises);

    message.success(forbid ? '停用成功' : '启用成功');
    run();
    clearRowSelection();
  };

  const deleteItem = async ({ ...obj }) => {
    console.log(obj);

    if (isDataset) {
      // await datasetService.deleteDatasetCollection(obj.id);
      await datasetService.deleteDatasetFile({
        // fileIds: [item?.fileId],
        ids: [obj?.fileId],
      });
    } else {
      await datasetService.datasetDelete({
        id: [obj?.id],
        reviewStatus: 'drop',
        app_id: obj.app_id,
      });
    }
  };

  const singleDelete = async (node: TreeData) => {
    if (!isPermit) {
      message.info('权限暂不支持该操作');
      return;
    }

    setDeleteModalVisible(true);
    setBatchDelete(false);
    setCurrentEditTreeData(node);
  };

  useEffect(() => {
    if (isDelete) {
      handleDatasetBatchClick();
    }
  }, [isDelete]);

  const handleDatasetBatchClick = async () => {
    if (!isPermit) {
      message.info('权限暂不支持该操作');
      return;
    }

    setDeleteModalVisible(true);
    setBatchDelete(true);
  };

  const handleDeleteCancel = () => {
    setDeleteModalVisible(false);
    setIsDelete(false);
  };

  const checkPage = () => {
    const newTotalPages = Math.max(Math.ceil(total / pageSize), 1);
    if (page > newTotalPages) {
      setPage(newTotalPages);
    }
  };

  const handleDeleteConfirm = async () => {
    try {
      setLoading(true);
      // console.log(selectedTreeKeys);
      // console.log(currentEditTreeData);

      if (batchDelete) {
        // 判断数据是知识库还是文档 根据fullTreeData判断数据类型
        if (fullTreeData[0].fileId !== undefined) {
          await datasetService.deleteDatasetFile({
            ids: selectedTreeKeys,
          });
        } else {
          const promises = selectedTreeKeys.map(async (key, i) => {
            await deleteItem({
              id: key,
              app_id: appId,
              dataset_type: checkedTreeDatas[i]?.type,
            });
          });
          await Promise.all(promises);
        }

        // checkPage(selectedTreeKeys.length);

        message.success('删除成功');
        // event$?.emit(DatasetEvent.UPDATEDATASETTREE);
        run();
        clearRowSelection();
      } else {
        if (!currentEditTreeData) {
          return;
        }
        if (currentEditTreeData.fileId !== undefined) {
          // console.log(3, currentEditTreeData);
          // return;
          // 入库后走审批，未入库不走审批
          if (currentEditTreeData.reviewStatus === 'upload_reject') {
            await datasetService.deleteApprovalDocument({
              ids: [currentEditTreeData?._id],
              appId,
            });
          } else {
            await datasetService.deleteDatasetFile({
              // fileIds: [currentEditTreeData?.fileId],
              ids: [currentEditTreeData?._id],
            });
          }
        } else {
          await deleteItem({
            id: currentEditTreeData?.id,
            app_id: appId,
            dataset_type: currentEditTreeData?.type,
          });
        }

        message.success('删除成功');
        // event$?.emit(DatasetEvent.UPDATEDATASETTREE);  去掉这个
        run();
      }
      setDeleteModalVisible(false);
      setIsDelete(false);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const onCheckboxChange: CheckboxProps['onChange'] = (e) => {
    setIsCheckedAll(e.target.checked);
    // 仅选择当前可见且可勾选的节点（与 Tree 的 disableCheckbox 规则一致）
    const canSelect = (node: TreeData) => {
      const isFileLocked =
        node.reviewStatus === 'upload_publish' ||
        node.reviewStatus === 'delete_publish' ||
        node.reviewStatus === 'delete_reject';
      const isOtherGroup = !getIsEditPermission(users, node) && node.groupId !== groupId;
      return !(isFileLocked || isOtherGroup);
    };

    const treeDatas = filterTree(
      filteredTreeData.filter(canSelect),
      searchData,
      false,
      DatasetTypeEnum.api,
    );
    const keys = e.target.checked ? treeDatas.map((item) => String(item.key)) : [];
    setSelectedTreeKeys(keys);
    setCheckedTreeDatas(treeDatas);
  };

  const onClosePreview = () => {
    setIsPreview(false);
  };
  const changeIgnore = async (node: TreeData) => {
    await datasetService.reviewApprovalDocument({
      ids: [node._id as string],
      operator: 'delete',
      reason: '',
      appId: node.appId,
      groupId: node.groupId,
      reviewStatus: 'delete_reject_ignore',
    });
    message.success('忽略成功');
    run();
  };

  return (
    <>
      <div className="mb-2 h-full overflow-y-auto">
        {
          <div className="flex h-full flex-col">
            {/* <div className="mb-2 mt-2 flex items-center justify-between">
              <div style={{ marginLeft: '38px' }} className="w-1/2">
                <Checkbox
                  disabled={!(selectedTreeData && selectedTreeData.length > 0)}
                  checked={isCheckedAll}
                  onChange={onCheckboxChange}
                >
                  全选
                </Checkbox>
              </div>
              <Input
                placeholder="搜索..."
                className="mb-2 mr-[38px] !w-[200px] !border-0 bg-[white] text-sm"
                value={searchValue}
                prefix={<SearchOutlined style={{ color: '#C9CEE2', marginRight: '10px' }} />}
                onChange={(e) => {
                  setSearchValue(e.target.value);
                }}
              />
            </div> */}
            {loading || dataLoading ? (
              <div className="h-full min-h-32 w-full items-center justify-center">
                <Spin className="w-full" tip="Loading..." />
              </div>
            ) : (
              <div
                className="flex h-full w-full flex-col"
                style={{ height: 'calc(100vh - 210px)' }}
              >
                {showList ? (
                  <div className="flex w-full flex-col pl-4 pr-4">
                    <Row
                      className="tree-header flex h-[44px] !items-center rounded-lg bg-[#F7F8FA] px-2 pl-4"
                      justify="space-between"
                      align="bottom"
                    >
                      <Col span={4}>
                        <div className="flex">
                          <div style={showType == 'dataset' ? { visibility: 'hidden' } : {}}>
                            <Checkbox
                              disabled={!(selectedTreeData && selectedTreeData.length > 0)}
                              checked={isCheckedAll}
                              onChange={onCheckboxChange}
                              className="check-box"
                            >
                              {/* <span className="m-2">全选</span> */}
                            </Checkbox>
                          </div>
                          <div className="ml-5 self-center truncate text-sm font-semibold text-text-3">
                            名称
                          </div>
                        </div>
                      </Col>
                      {showType === 'dataset' && (
                        <Col span={4}>
                          <div
                            className="ml-9 self-center truncate text-sm font-semibold text-text-3"
                            style={showType !== 'dataset' ? { display: 'none' } : {}}
                          >
                            文档类型
                          </div>
                        </Col>
                      )}
                      {showType === 'dataset' && (
                        <Col span={4}>
                          <div
                            className="ml-7 self-center truncate text-sm font-semibold text-text-3"
                            style={showType !== 'dataset' ? { display: 'none' } : {}}
                          >
                            所属组织
                          </div>
                        </Col>
                      )}

                      {showType !== 'dataset' && (
                        <Col span={2}>
                          <div
                            className="ml-7 self-center truncate text-sm font-semibold text-text-3"
                            onClick={handleDateSortClick}
                          >
                            过期时间
                          </div>
                        </Col>
                      )}

                      <Col span={4}>
                        <div
                          className="ml-7 self-center truncate text-sm font-semibold text-text-3"
                          onClick={handleDateSortClick}
                          style={{ cursor: 'pointer' }}
                        >
                          {renderDateSortTitle()}
                        </div>
                      </Col>
                      <Col span={2}>
                        <div
                          className="ml-2 self-center truncate text-sm font-semibold text-text-3"
                          style={showType == 'dataset' ? { display: 'none' } : {}}
                        >
                          {renderHeaderWithFilter(
                            '状态',
                            statusOptions,
                            statusFilter,
                            setStatusFilter,
                          )}
                        </div>
                      </Col>
                      <Col span={2}>
                        <div
                          className="self-center truncate text-sm font-semibold text-text-3"
                          style={showType == 'dataset' ? { display: 'none' } : {}}
                        >
                          {renderHeaderWithFilter(
                            '启/停用',
                            forbidOptions,
                            forbidFilter,
                            setForbidFilter,
                          )}
                        </div>
                      </Col>

                      <Col span={4}>
                        <div className="ml-[-4px] text-sm font-semibold text-text-3">操作</div>
                      </Col>
                    </Row>
                    <Tree
                      className={`table-tree h-[470px] w-full overflow-y-auto rounded-xl ${
                        isPc ? '' : 'phone-tree'
                      }`}
                      checkedKeys={selectedTreeKeys}
                      checkStrictly
                      blockNode
                      checkable
                      onCheck={onCheck}
                      onSelect={onSelect}
                      // treeData={treeData}
                      treeData={filterTree(
                        filteredTreeData.map((node) => ({
                          ...node,
                          disableCheckbox:
                            ((node.reviewStatus === 'upload_publish' ||
                              node.reviewStatus === 'delete_publish') &&
                              node.fileId !== undefined) ||
                            (node.groupId !== ungroupedId && !getIsEditPermission(users, node)),
                        })),
                        searchData,
                        false,
                        DatasetTypeEnum.api,
                      )}
                      titleRender={titleRender}
                      switcherIcon={<span style={{ display: 'none' }} />}
                    />
                    {!showList && !loading && <EmptyPage description="暂无数据" />}
                    {
                      <div
                        style={{ position: 'absolute', bottom: '0', width: 'calc(100% - 300px' }}
                      >
                        {/* <div className="mb-5 ml-auto mr-5">
                          <Pagination
                            total={total}
                            defaultPageSize={pageSize}
                            defaultCurrent={page}
                            pageSize={pageSize}
                            current={page}
                            showSizeChanger={
                              selectedTreeData &&
                              selectedTreeData.length > 0 &&
                              selectedTreeData[selectedTreeData.length - 1].type ===
                                DatasetTypeEnum.dataset
                            }
                            onChange={onChange}
                          />
                        </div> */}
                        <div className="flex items-center justify-between border-t border-gray-200 py-6">
                          <div className="pagination-total text-gray-600">
                            共 <span className="text-blue-600 font-medium">{total || 0}</span>{' '}
                            项数据
                          </div>

                          <Pagination
                            total={total}
                            defaultPageSize={pageSize}
                            defaultCurrent={page}
                            pageSize={pageSize}
                            current={page}
                            showSizeChanger={
                              selectedTreeData &&
                              selectedTreeData.length > 0 &&
                              selectedTreeData[selectedTreeData.length - 1].type ===
                                DatasetTypeEnum.dataset
                            }
                            onChange={onChange}
                            showQuickJumper
                          />
                        </div>
                      </div>
                    }
                  </div>
                ) : (
                  <NotData iconSize={80} textClassName="text-sm" />
                )}
              </div>
            )}
          </div>
        }
      </div>

      {/* {selectedTreeKeys.length > 0 && (
        <div
          className="animated-div"
          style={{
            position: 'fixed',
            bottom: '5%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: '#474C5F',
            borderRadius: '50px',
          }}
        >
          <Space className="ml-2 mr-2" style={{ height: '45px' }}>
            <Button
              style={{ color: '#fff' }}
              type="text"
              icon={<CloseOutlined />}
              onClick={clearRowSelection}
            />
            <span className="whitespace-nowrap text-nowrap text-xs" style={{ color: '#8E93A4' }}>
              已选 {selectedTreeKeys.length} 项
            </span>
            <Splitter />
            {isDataset && (
              <Button
                style={{ color: '#fff' }}
                type="text"
                onClick={() => {
                  onStatusClicked(false);
                }}
              >
                启用
              </Button>
            )}
            {isDataset && (
              <Button
                style={{ color: '#fff' }}
                type="text"
                onClick={() => {
                  onStatusClicked(true);
                }}
              >
                停用
              </Button>
            )}
            <Button style={{ color: '#fff' }} type="text" onClick={handleDatasetBatchClick}>
              删除
            </Button>
          </Space>
        </div>
      )} */}

      <FilePreviewDrawer
        fileName=""
        loading={loading}
        setLoading={setLoading}
        open={isPreview}
        previewUrl={previewUrl}
        onClose={onClosePreview}
      />
      <DeleteConfirmModal
        visible={deleteModalVisible}
        loading={loading}
        text="确定要删除吗？"
        onCancel={handleDeleteCancel}
        onConfirm={handleDeleteConfirm}
      />

      <DatasetApproveModal
        isModalOpen={isReapproval}
        setIsModalOpen={setIsReapproval}
        onSuccessful={fetchCollections}
        approvalData={approvalData}
      />

      <ExpirationTimeModal
        open={modal.timeModal.isOpen}
        onCancel={modal.timeModal.close}
        onOk={() => {
          run();
        }}
      />

      <TipsModals
        okText="删除"
        centered
        open={modal.deleteModal.isOpen}
        onOk={() => {
          if (!isPermit) {
            message.info('权限暂不支持该操作');
            return;
          }
          setBatchDelete(false);

          handleDeleteConfirm();
          modal.deleteModal.close();
        }}
        onCancel={modal.deleteModal.close}
      >
        删除文件需要管理员审批后才会生效
      </TipsModals>
    </>
  );
}

export default memo(DatasetsTreeList);
